<template>
  <div class="login">
    <div class="loginDiv">
      <div class="leftIcon" />
      <el-form ref="loginForm" v-loading="formLoadIng" :model="loginForm" :rules="loginRules" class="login-form login-form-main">
        <div v-if="tenantCompanyInfo.logo" class="logo-base64">
          <img :src="tenantCompanyInfo.logo" :width="tenantCompanyInfo.width ? tenantCompanyInfo.width : 50" :height="tenantCompanyInfo.height ? tenantCompanyInfo.height : 50" alt="">
        </div>
        <div v-else class="logo" />
        <h3 v-if="tenantCompanyInfo.logo" class="title">{{ tenantCompanyInfo.name }}</h3>
        <h3 v-else class="title">{{ $t('贷后管理系统') }}</h3>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="new-password"
            clearable
            :placeholder="$t('账号')"
            @change="captchaImageShow"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="new-password"
            clearable
            :placeholder="$t('密码')"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item v-if="tenant === 'true'" prop="tenantCode">
          <el-input
            v-model="loginForm.tenantCode"
            type="text"
            auto-complete="off"
            clearable
            :placeholder="$t('机构编号')"
            @blur="getLanguage"
          >
            <svg-icon slot="prefix" icon-class="code" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item v-if="loginFailNum >= 3" prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            :placeholder="$t('验证码')"
            style="width: 63%"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode">
          </div>
        </el-form-item>
        <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;margin-top: 10px;"
            @keyup.enter.native="handleLogin"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">{{ $t('登 录') }}</span>
            <span v-else>{{ $t('登 录 中') }}...</span>
          </el-button>
        </el-form-item>
        <div class="pswRow">
          <div class="item left">
            <el-checkbox v-model="rememberMe">{{ $t('记住密码') }}</el-checkbox>
          </div>
          <div class="item right">
            <span @click="toReset">{{ $t('忘记密码') }}</span>
          </div>
        </div>
      </el-form>
    </div>
    <!-- <a class="pub-icon" href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzU4OTgyNDA4NQ==&action=getalbum&album_id=2120720597201551370#wechat_redirect" target="_blank">
      <i class="pub" />J博士公开课及回放
    </a> -->

    <contactUs ref="contactUs" />
  </div>
</template>

<script>
import { getCodeImg, getTenant, captchaImageShow, getTenantInfo } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getLanguage } from '@/api/dev/language/sysLanguage'
import contactUs from '@/views/contactUs'
export default {
  name: 'Login',
  components: {
    contactUs
  },
  data() {
    return {
      codeUrl: '',
      cookiePassword: '',
      // 是否多租户模式
      tenant: 'false',
      // 登录失败次数
      loginFailNum: 0,
      // 等待框
      formLoadIng: false,
      loginForm: {
        username: '',
        password: '',
        tenantCode: '',
        code: '',
        uuid: ''
      },
      rememberMe: true,
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        password: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        tenantCode: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        code: [{ required: true, trigger: 'change', message: this.$t('必填信息') }]
      },
      loading: false,
      redirect: undefined,
      tenantCompanyInfo: {
        logo: undefined,
        name: undefined,
        width: undefined,
        height: undefined
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
    // 查询是否多租户
    this.getTenant()
    // 获取租户logo和名称
    this.getTenantInfo()
  },
  mounted() {
    // 绑定登录页回车键登录事件
    window.addEventListener('keydown', this.keyDown)
  },
  // 增加登录页回车键登录功能
  methods: {
    toOpen(href) {
      window.open(href, '_blank')
    },
    keyDown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    chat() {
      if (this.$refs.contactUs?.visible !== undefined) {
        this.$refs.contactUs.visible = true
      }
    },
    toReset() {
      this.$router.push({ path: '/recoverpw' })
    },
    getCode() {
      if (this.loginFailNum >= 3) {
        getCodeImg().then(res => {
          this.codeUrl = 'data:image/gif;base64,' + res.datas.img
          this.loginForm.uuid = res.datas.uuid
        })
      }
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const tenantCode = Cookies.get('tenantCode')

      var tenantCompanyInfo = window.localStorage.getItem('tenantCompanyInfo')
      if (tenantCompanyInfo) {
        try {
          this.tenantCompanyInfo = JSON.parse(tenantCompanyInfo)
        } catch (e) {
          console.log(e)
        }
      }

      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        tenantCode: tenantCode === undefined ? undefined : tenantCode
      }
      if (username === undefined) {
        this.rememberMe = false
      }
    },
    // 获取是否展示验证码
    captchaImageShow() {
      if (this.loginForm.username !== undefined && this.loginForm.username !== '') {
        captchaImageShow(this.loginForm.username).then(res => {
          if (res.data) {
            this.loginFailNum = 3
            this.getCode()
          }
        })
      }
    },
    /**
     * 获取是不是多租户模式
     */
    getTenant() {
      this.formLoadIng = true
      getTenant().then(res => {
        if (res !== undefined) {
          this.tenant = res.data
        }
      })
    },
    // 获取当前租户的logo和名称
    getTenantInfo(tenantCode) {
      // 从url中获取租户code
      if (tenantCode === undefined) {
        tenantCode = this.$route.query.tenantCode
      }
      if (tenantCode !== undefined) {
        this.loginForm.tenantCode = tenantCode
      }
      getTenantInfo(this.loginForm.tenantCode).then(res => {
        if (res.data !== null) {
          this.tenantCompanyInfo.logo = res.data.productLogo
          this.tenantCompanyInfo.name = res.data.productName
          this.tenantCompanyInfo.width = res.data.productLogoWidth
          this.tenantCompanyInfo.height = res.data.productLogoHeight
        } else {
          this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        }
        console.log(JSON.stringify(this.tenantCompanyInfo))
        window.localStorage.setItem('tenantCompanyInfo', JSON.stringify(this.tenantCompanyInfo))
        this.formLoadIng = false
      }).catch(() => {
        this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        this.formLoadIng = false
      })
    },
    // 更新失败次数
    addLoginFailNum() {
      this.loginFailNum++
    },
    getLanguage() {
      getLanguage(undefined, this.loginForm.tenantCode).then(response => {
        var localStorage = window.localStorage.getItem('language')
        if (localStorage === undefined || localStorage === null || localStorage === 'null') {
          localStorage = 'zh_cn'
        }
        this.$i18n.vm.messages[localStorage] = response.languageData
        // 修改国际化词条
        window.localStorage.setItem('language_' + localStorage, JSON.stringify(response.languageData))
        window.localStorage.setItem('language', localStorage)
        this.$i18n.locale = localStorage
      })
      this.getTenantInfo(this.loginForm.tenantCode)
    },
    handleLogin() {
      console.log('登录')
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('tenantCode', this.loginForm.tenantCode, { expires: 30 })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('tenantCode')
          }

          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              this.$router.push({ path: '/index' || '/', name: '首页', params: { once: 1 }})
              this.$store.state.permission.leftActive = this.$store.state.permission.navActive = '999'
            })
            .catch((err) => {
              if (err === '验证码已失效') {
                this.loading = false
                this.loginFailNum = 3
                this.getCode()
              } else {
                this.loading = false
                // 更新登录失败次数
                this.addLoginFailNum()
                this.getCode()
              }
            })
        }
      })
    }

  }
}
</script>
<style scoped lang="scss">
.pub-icon{
  position: fixed;
  right: 20px;
  top: 20px;
  display: flex;
  align-items: center;
  font-weight: bold;
  background-image: linear-gradient(0deg, #04c5dc, #069cf3);
  background-clip:text;
  -webkit-background-clip:text;
  color: transparent;
  .pub{
    display: inline-block;
    width: 25px;
    height: 25px;
    background-size: cover;
    background-image: url();
  }
}
.login .el-login-footer{
  height: unset!important;
  line-height: unset!important;
  bottom: 5px!important;
  .links{
    margin: 0;
    margin-bottom: 5px;
    a{
      text-decoration: underline;
    }
  }
}
</style>
